//
//  PublishViewController.m
//  Find
//
//  Created by lanou3g on 15/10/27.
//  Copyright © 2015年 Reiko. All rights reserved.
//

#import "PublishViewController.h"
#import "PublishDetailView.h"
#import "MessagePhotoView.h"
#import "MapViewController.h"
#import "LostMessageModel.h"
#import "FindMessageModel.h"
#import "UIImage+ChangeImageSize.h"







@interface PublishViewController ()<MessagePhotoViewDelegate , UIImagePickerControllerDelegate,UINavigationControllerDelegate,MapDelegate>
@property (nonatomic, retain)MessagePhotoView *photoView;
@property (nonatomic, retain)PublishDetailView *publishDetailView;
@property (nonatomic, retain)NSMutableArray *photoItems;
@property (nonatomic, retain)NSMutableArray *imageArray;
// 经longitude纬latitude度
@property (nonatomic, assign)CGFloat longitude;
@property (nonatomic, assign)CGFloat latitude;
@property (nonatomic, assign)BOOL isPublish;


@end

@implementation PublishViewController

- (void)viewDidLoad {
    [super viewDidLoad];

    self.view.backgroundColor = [UIColor whiteColor];
    self.publishDetailView = [[PublishDetailView alloc] initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight-kNavBarHeight)];
    [self.view addSubview:self.publishDetailView];
    [self addNavigationItem];
    // 地图添加点击事件
    [self.publishDetailView.mapButton addTarget:self action:@selector(actionMapButton:) forControlEvents:UIControlEventTouchUpInside];
    // 相册添加点击事件
    [self.publishDetailView.photoButton addTarget:self action:@selector(actionPhotoButton:) forControlEvents:UIControlEventTouchUpInside];
    // 相机添加点击事件
    [self.publishDetailView.cameraButton addTarget:self action:@selector(actionCameraButton:) forControlEvents:UIControlEventTouchUpInside];
    self.imageArray = [NSMutableArray array];
}
#pragma mark -- 设置itembar
- (void)addNavigationItem
{
    UILabel *label = [[UILabel alloc] initWithFrame:CGRectMake(0, 0, 200, 60)];
    label.textAlignment = NSTextAlignmentCenter;
    label.font = [UIFont fontWithName:@"Helvetica" size:18];
    label.textColor = [UIColor whiteColor];
    self.navigationItem.titleView = label;

    if ([self.publishInfoType isEqualToString:@"lost"]) {
        label.text = @"寻物启事";
    } else {
        label.text = @"失物招领";
    }
    UIBarButtonItem *backBarButton = [[UIBarButtonItem alloc] initWithTitle:@"取消" style:UIBarButtonItemStylePlain target:self action:@selector(actionBackBarButton:)];
    self.navigationItem.leftBarButtonItem = backBarButton;
    self.navigationItem.leftBarButtonItem.tintColor = [UIColor whiteColor];
    UIBarButtonItem *sentBarButton = [[UIBarButtonItem alloc] initWithTitle:@"发送" style:UIBarButtonItemStylePlain target:self action:@selector(actionSentBarButton:)];
    self.navigationItem.rightBarButtonItem = sentBarButton;
     self.navigationItem.rightBarButtonItem.tintColor = [UIColor whiteColor];
     [self.navigationController.navigationBar setBackgroundImage:[UIImage imageNamed:@"iconfont-navbar-back"] forBarMetrics:UIBarMetricsDefault];
   
}
#pragma mark -- 取消按钮的点击事件
- (void)actionBackBarButton:(UIBarButtonItem *)backBarButton
{
    [self.publishDetailView.titleTextView resignFirstResponder];
    [self.publishDetailView.contextTextView resignFirstResponder];
    [self performSelector:@selector(dismissViewController) withObject:self afterDelay:0.5];
}
- (void)dismissViewController{
    [self dismissViewControllerAnimated:YES completion:nil];
}


#pragma mark -- 发送按钮的点击事件
- (void)actionSentBarButton:(UIBarButtonItem *)sentBarButton
{
    //
    if (self.isPublish) {
        return;
    }
    if ([self.publishDetailView.titleTextView.text isEqualToString:@""] ||[self.publishDetailView.contextTextView.text isEqualToString:@""] ) {
        [self showAlterViewWithTitle:@"提示" Message:@"标题和内容不能为空"];
    } else {
        self.isPublish = YES;
           [SVProgressHUD showWithStatus:@"正在发布"];
        if (self.photoItems.count == 0) {
            if ([self.publishInfoType isEqualToString:@"find"]) {
                [self postModelWithArray1:nil];
            } else {
                [self postModelWithArray2:nil];
            }
    }
   __block NSInteger i = 1;
        for (ALAsset *asset in self.photoItems) {
            CGImageRef ref = [[asset defaultRepresentation]fullScreenImage];
            UIImage *img = [[UIImage alloc]initWithCGImage:ref];
            UIImage *imag = [UIImage imageWithImageSimple:img scaledToSize:CGSizeMake(kScreenWidth, kScreenWidth)];
            NSData* imageData = UIImagePNGRepresentation(imag);
            AVFile *file = [AVFile fileWithData:imageData];
            [file saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                if (succeeded) {
                    NSInteger j = 1;
                    if (i == self.photoItems.count && j == 1){
                        j++;
                        if ([self.publishInfoType isEqualToString:@"find"]) {
                             [self postWithUrl:file.url flag:@"find"];
                        } else {
                             [self postWithUrl:file.url flag:@"lost"];
                        }
                       
                        i++;
                    } else{
                        [self postWithUrl:file.url flag:nil];
                        i++;
                    }
                } else {
                }
            }];
        }
        
    }
}
- (void)postWithUrl:(NSString *)url flag:(NSString *)flag
{
    [self.imageArray addObject:url];
    if ([flag isEqualToString:@"find"]) {
        [self postModelWithArray1:self.imageArray];
    } else if ([flag isEqualToString:@"lost"]){
        [self postModelWithArray2:self.imageArray];
    }
}

- (void)postModelWithArray1:(NSMutableArray *)array
{
    
    AVUser *user = [AVUser currentUser];
    FindMessageModel *findModel = [[FindMessageModel alloc] init];
    findModel.user = user;
    findModel.context = self.publishDetailView.contextTextView.text;
   
    findModel.location = [NSString stringWithFormat:@"%@",self.address];
    findModel.imageArray = array;
    findModel.title = self.publishDetailView.titleTextView.text;
    findModel.longitude = [NSNumber numberWithFloat:self.longitude];
    findModel.latitude =  [NSNumber numberWithFloat:self.latitude];
    [findModel saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
        if (error) {
            [SVProgressHUD showErrorWithStatus:@"发布失败"];
            [SVProgressHUD dismissWithDelay:2];
        } else {

            AVRelation *publishFind = [user relationforKey:@"publishFind"];
            [publishFind addObject:findModel];
            [user saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                if (succeeded) {
                    [SVProgressHUD showWithStatus:@"发布成功"];
                    [SVProgressHUD dismissWithDelay:0.5];
                } else {
                }
            }];

            [self dismissViewControllerAnimated:YES completion:nil];
       }
    }];
}

- (void)postModelWithArray2:(NSMutableArray *)array
{
  
    AVUser *user = [AVUser currentUser];
    LostMessageModel *lostModel = [[LostMessageModel alloc] init];
    lostModel.user = user;
    lostModel.context = self.publishDetailView.contextTextView.text;
    lostModel.location = self.address;
    lostModel.imageArray = array;
    lostModel.title = self.publishDetailView.titleTextView.text;
    lostModel.longitude = [NSNumber numberWithFloat:self.longitude];
    lostModel.latitude  =  [NSNumber numberWithFloat:self.latitude];

    [lostModel saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
        if (error) {
        } else {
            AVRelation *publishLost = [user relationforKey:@"publishLost"];
            [publishLost addObject:lostModel];
            [user saveInBackgroundWithBlock:^(BOOL succeeded, NSError *error) {
                if (succeeded) {
                     [SVProgressHUD showWithStatus:@"发布成功"];
                    [SVProgressHUD dismissWithDelay:2];
                } else {
                }
            }];

            [self dismissViewControllerAnimated:YES completion:nil];
         }
    }];
            
}

#pragma mark -- 地图按钮的点击事情
- (void)actionMapButton:(UIButton *)mapButton
{
    MapViewController *map = [[MapViewController alloc] init];
    map.mapDelegate = self;
    map.address = self.publishDetailView.addressTextField.text;
    [self.navigationController pushViewController:map animated:YES];
}
#pragma mark --地图的代理方法
- (void)transAddress:(NSString *)address latitude:(float)latitude longitude:(float)longitude
{
    self.publishDetailView.addressTextField.text = address;
    self.address = address;
    // 经longitude纬latitude度
    self.longitude = longitude;
    self.latitude = latitude;
   
}
#pragma mark --  相册按钮的点击事情
- (void)actionPhotoButton:(UIButton *)photoButton
{

    self.photoView = [[MessagePhotoView alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(self.publishDetailView.contextTextView.frame)+(kScreenHeight-329)*0.1, kScreenWidth, 180)];
  //  self.photoView.backgroundColor = [UIColor cyanColor];
    self.photoView.delegate = self;
    [self.view addSubview:self.photoView];
    [self.photoView localPhoto];
//    [self.view sendSubviewToBack:self.photoView];
 
}

#pragma mark -- 相机按钮的点击事情
- (void)actionCameraButton:(UIButton *)cameraButton
{
    [self openCamera];
    
}
#pragma mark -- 打开相机的方法
- (void)openCamera
{
    UIImagePickerControllerSourceType sourceType = UIImagePickerControllerSourceTypeCamera;
    if([UIImagePickerController isSourceTypeAvailable:UIImagePickerControllerSourceTypeCamera]){
        UIImagePickerController *picker = [[UIImagePickerController alloc]init];
        picker.delegate = self;
        //设置拍照后的图片可被编辑
        picker.allowsEditing = YES;
        picker.sourceType = sourceType;
        [self presentViewController:picker animated:YES completion:nil];
       
    }else{
    }
}
#pragma mark --  拍摄完成后或者选择相册完成后自动调用的方法
- (void)imagePickerController:(UIImagePickerController *)picker didFinishPickingMediaWithInfo:(NSDictionary *)info
{
   // UIImage *image  = [info objectForKey:UIImagePickerControllerOriginalImage];
   
   // NSData* imageData = UIImagePNGRepresentation(image);
    
    [self dismissViewControllerAnimated:YES completion:nil];
    
}
#pragma mark -- 代理方法,取得相册的图片
- (void)getPhotoMenuItems:(NSMutableArray *)photoItems
{
    self.photoItems = photoItems;

}
#pragma mark -- 移除相册的视图
- (void)removeImageView
{
    [self.photoView removeFromSuperview];
}

- (void)addPicker:(UIImagePickerController *)picker
{
    [self presentViewController:picker animated:YES completion:nil];
}
// 点击空白处回收
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:YES];
}
// 封装一个alertView
- (void)showAlterViewWithTitle:(NSString *)title Message:(NSString *)message
{
    
    UIAlertController *alertView = [UIAlertController alertControllerWithTitle:title message:message preferredStyle:UIAlertControllerStyleAlert];
    [self performSelector:@selector(closeAlter:) withObject:alertView afterDelay:1];
    
    [self presentViewController:alertView animated:YES completion:nil];
}

// 设置1秒之后消失
- (void)closeAlter:(UIAlertController *)alert
{
    [alert dismissViewControllerAnimated:YES completion:nil];
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
   
}



@end
